<template>
  <div class="app-container">
    讲师表单
    <el-form label-width="120px" ref="eduTeacher" :model="eduTeacher" :rules="rules">
      <el-form-item label="讲师名称" prop="name">
        <el-input v-model="eduTeacher.name" />
      </el-form-item>
      <el-form-item label="讲师排序" prop="sort">
        <el-input-number
          v-model="eduTeacher.sort"
          controls-position="right"
          min="0"
        />
      </el-form-item>
      <el-form-item label="讲师头衔" prop="level">
        <el-select v-model="eduTeacher.level" clearable placeholder="请选择">
          <!--
              数据类型一定要和取出的json中的一致，否则没法回填
              因此，这里value使用动态绑定的值，保证其数据类型是number
            -->
          <el-option :value="1" label="高级讲师" prop="label"/>
          <el-option :value="2" label="首席讲师" prop="label"/>
        </el-select>
      </el-form-item>
      <el-form-item label="讲师资历" prop="career">
        <el-input v-model="eduTeacher.career" />
      </el-form-item>
      <el-form-item label="讲师简介" prop="intro">
        <el-input v-model="eduTeacher.intro" :rows="10" type="textarea" />
      </el-form-item>

      <el-form-item label="讲师头像" prop="avatar">
        <!-- 头衔缩略图 -->
        <pan-thumb :image="eduTeacher.avatar" />
        <!-- 文件上传按钮 -->
        <el-button
          type="primary"
          icon="el-icon-upload"
          @click="imagecropperShow = true"
          >更换头像
          </el-button>

        <!--
v-show：是否显示上传组件
:key：类似于id，如果一个页面多个图片上传控件，可以做区分
:url：后台上传的url地址
@close：关闭上传组件
        @crop-upload-success：上传成功后的回调-->
        <image-cropper
          v-show="imagecropperShow"
          :width="300"
          :height="300"
          :key="imagecropperKey"
          :url="BASE_API + '/eduoss/fileoss/uploadFile'"
          field="file"
          @close="close"
          @crop-upload-success="cropSuccess"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { validatanum } from '@/utils/validate'
import { validataisnotnull } from '@/utils/validate'
import teacher from "@/api/teacher";
import ImageCropper from "@/components/ImageCropper";
import PanThumb from "@/components/PanThumb";
export default {
  components: { ImageCropper, PanThumb },
  data() {
    const validateTeacherSort = (rule, value, callback) => {
      if (!validatanum(value)) {
        callback(new Error('请输入正确的数字'))
      } else {
        callback()
      }
    }
    const validateTeacherisnotnull= (rule, value, callback) => {
      if (!validataisnotnull(value)) {
        callback(new Error('不可以为空'))
      } else {
        callback()
      }
    }
    return {

      eduTeacher: {}, 
      //表单数据
      saveBtnDisabled: false, //这个是判断这个按是不是不可以用，默认是true，不可以用
      BASE_API: process.env.BASE_API, // 接口API地址
      imagecropperShow: false, // 是否显示上传组件
      imagecropperKey: 0, // 上传组件id
      rules: {
        name: [
            { required: true, message: '请输入讲师名称', trigger: 'blur' },
            { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
          ],
          sort: [{ required: true, trigger: 'blur', validator: validateTeacherSort }],
          level: [{ required: true, trigger: 'blur',validator: validateTeacherisnotnull }],
          career: [
            { required: true, message: '请输入讲师资历', trigger: 'blur' },
            { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
          ],
          intro: [
            { required: true, message: '请输入讲师简介', trigger: 'blur' },
            { min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }
          ],
      },
    };
  },
  // 多个操作公用一个组件，我们需要回归测试，我们就需要用watch来监听他们，发生了变化，要记得清空数据
  created() {
    console.log("created");
    this.init();
  },
  watch: {
    // 监听器，监听我们vue中所有属性
    $route(to, from) {
      console.log("created");
      this.init();
    },
  },
  methods: {
    init() {
      //获取路由中的id
      // console.log('$route.params.id='+this.$route.params.id)
      if (this.$route.params && this.$route.params.id) {
        teacher.getTeacherById(this.$route.params.id).then((response) => {
          //数据回显
          this.eduTeacher = response.data.teacher;
        });
      } else {
        console.log("清空数据");
        this.eduTeacher = {};
      }
    },
    //判断表单数据是否全部填满
    isEduTeacherForm() {
      if (
        (((this.eduTeacher.name != null && this.eduTeacher.sort) != null &&
          this.eduTeacher.level) != null && this.eduTeacher.career) != null
      )
        this.saveBtnDisabled = false;
    },
    saveOrUpdate() {
      if (this.eduTeacher.id) {
        //id存在执行更新
        this.updateTeacherInfo();
      } else {
        this.saveTeacher();
      }
    },
    saveTeacher() {
      teacher.addTeacher(this.eduTeacher).then((response) => {
        //到这里一定成功了，因为失败了都被拦截了
        //1.提示成功
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        //2.跳转到查询讲师那里
        //路由跳转
        this.$router.push({ path: "/teacher/list" });
      });
    },
    updateTeacherInfo() {
      teacher.updateTeacher(this.eduTeacher).then((response) => {
        //到这里一定成功了，因为失败了都被拦截了
        //1.提示成功
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        //2.跳转到查询讲师那里
        //路由跳转
        this.$router.push({ path: "/teacher/list" });
      });
    },
    close(){
      //关闭操作
      this.imagecropperShow = false

      //imagecropperKey这个东西要每次上传他都不一样才行
      this.imagecropperKey=this.imagecropperKey+1
    },
    cropSuccess(data){
      //成功后的回调函数
      //获取出url，显示在页面
      this.eduTeacher.avatar=data.url
      //关闭表格
      this.close()
    }
  },
};
</script>